package com.fly.jackson;

import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;

import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonDataParse
{
    static List<String> lines;
    
    /**
     * thread-safe
     */
    static ObjectMapper mapper = new ObjectMapper();
    
    @BeforeAll
    public static void init()
    {
        try
        {
            String jsonBody = IOUtils.toString(new ClassPathResource("data.json").getInputStream(), StandardCharsets.UTF_8);
            lines = IOUtils.readLines(new StringReader(mapper.readTree(jsonBody).toPrettyString()));
        }
        catch (IOException e)
        {
        }
    }
    
    @Test
    public void testUrlCount()
    {
        List<String> urls = lines.stream().filter(line -> StringUtils.contains(line, "\"url\" : ")).map(n -> StringUtils.substringBetween(n, " : \"", "\",")).collect(Collectors.toList());
        List<String> counts = lines.stream().filter(line -> StringUtils.contains(line, "\"viewCount\" : ")).map(n -> StringUtils.substringBetween(n, " : ", ",")).collect(Collectors.toList());
        
        // 待使用lambda改写
        Map<String, Long> map = new HashMap<>();
        for (int i = 0; i < urls.size(); i++)
        {
            map.put(urls.get(i), NumberUtils.toLong(counts.get(i)));
        }
        log.info("{}", map);
    }
}
